#!/bin/bash
###
 # @Author: Loganli
 # @Gitee: https://gitee.com/attacker
 # @email: admin@attacker.club
 # @Date: 2025-04-25 11:30:00
 # @Description: 通用Zabbix Agent 7.0.10安装脚本
 # curl https://raw.githubusercontent.com/attacker/wuyou.run/master/scripts/monitor/zabbix/zabbix-agent/zabbix-agent.sh -o zabbix-agent.sh | bash -s <zabbix_server_ip> <hostname> [active|agent]
###

ZBX_SERVER=$1 # zabbix服务器地址，必填参数
HOSTNAME=$2  # 主机名称，必填参数
mode=$3 # 模式，可选参数：active或agent(被动)，默认agent

# 如果没有传参，给出提示并退出
if [ -z "$ZBX_SERVER" ] || [ -z "$HOSTNAME" ]; then
    echo "使用方法: $0 <zabbix_server_ip> <hostname> [active|agent]"
    echo "例如: $0 192.168.1.100 web-server-01 agent"
    exit 1
fi

# 如果没有指定模式，默认为agent模式
if [ -z "$mode" ]; then
    mode="agent"
fi

# 创建临时目录
TEMP_DIR=$(mktemp -d)
cd $TEMP_DIR

# 下载Zabbix Agent二进制包
echo "开始下载Zabbix Agent 7.0.10静态二进制包..."
curl -fsSL -O --max-time 60 --retry 3 --retry-delay 10 https://cdn.zabbix.com/zabbix/binaries/stable/7.0/7.0.10/zabbix_agent-7.0.10-linux-3.0-amd64-static.tar.gz

# 检查下载是否成功
if [ ! -f zabbix_agent-7.0.10-linux-3.0-amd64-static.tar.gz ]; then
    echo "下载Zabbix Agent失败，请检查网络连接或手动下载"
    exit 1
fi

# 停止现有服务（如果有）
systemctl stop zabbix-agent 2>/dev/null || service zabbix-agent stop 2>/dev/null
systemctl stop zabbix-agent2 2>/dev/null || service zabbix-agent2 stop 2>/dev/null

# 清理现有安装
echo "清理现有的Zabbix Agent安装..."
yum remove -y zabbix-agent zabbix-agent2 2>/dev/null
rm -rf /opt/zabbix

# 创建目录结构
echo "创建Zabbix目录结构..."
mkdir -p /opt/zabbix/sbin
mkdir -p /opt/zabbix/etc/zabbix_agentd.d
mkdir -p /opt/zabbix/var/run
mkdir -p /var/log/zabbix
mkdir -p /etc/zabbix/zabbix_agentd.d

# 解压并安装
echo "解压并安装Zabbix Agent..."
tar -xzf zabbix_agent-7.0.10-linux-3.0-amd64-static.tar.gz
cp -f zabbix_agent-7.0.10-linux-3.0-amd64-static/zabbix_agentd /opt/zabbix/sbin/
chmod +x /opt/zabbix/sbin/zabbix_agentd

# 创建符号链接
ln -sf /opt/zabbix/sbin/zabbix_agentd /usr/sbin/zabbix_agentd
ln -sf /opt/zabbix/etc /etc/zabbix

# 设置主机名
Set_hostname() {
  echo "设置主机名为: $HOSTNAME"
  if [ -f /etc/hostname ]; then
    echo "$HOSTNAME" >/etc/hostname
  fi
  sed -i "/HOSTNAME/c HOSTNAME=$HOSTNAME" /etc/sysconfig/network 2>/dev/null || echo "HOSTNAME=$HOSTNAME" >>/etc/sysconfig/network 2>/dev/null
  hostname $HOSTNAME
  grep $HOSTNAME /etc/hosts || echo "127.0.0.1 $HOSTNAME" >>/etc/hosts
}

# 配置Zabbix Agent
Set_zabbix_conf(){
    echo "配置Zabbix Agent..."
    cat >/opt/zabbix/etc/zabbix_agentd.conf<<EOF
PidFile=/opt/zabbix/var/run/zabbix_agentd.pid
LogFile=/var/log/zabbix/zabbix_agentd.log
LogFileSize=0
Server=${ZBX_SERVER}
ServerActive=${ZBX_SERVER}
Hostname=$HOSTNAME
HostMetadata=Linux
# 启用远程命令
EnableRemoteCommands=1
# 超时设置
Timeout=30
# 允许所有接口
ListenIP=0.0.0.0
Include=/etc/zabbix/zabbix_agentd.d/*.conf
EOF

    # 根据模式调整配置
    if [ "$mode" == "active" ]; then
        echo "配置为主动模式..."
        sed -i '/Server=/d' /opt/zabbix/etc/zabbix_agentd.conf
        sed -i '4a StartAgents=0' /opt/zabbix/etc/zabbix_agentd.conf
    else
        echo "配置为被动模式..."
    fi
    
    # 下载额外的配置文件
    echo "下载额外的配置文件..."
    curl -fsSL -O --max-time 30 --retry 3 --retry-delay 6 http://wuyou.run/scripts/monitor/zabbix/zabbix-agent/zabbix_agentd.d.tar.gz
    
    # 检查下载是否成功
    if [ -f zabbix_agentd.d.tar.gz ]; then
        # 解压到配置目录
        tar zxvf zabbix_agentd.d.tar.gz -C /etc/zabbix/zabbix_agentd.d/ --strip-components 1
        echo "已安装额外的监控配置"
    else
        echo "额外配置文件下载失败，将使用基本配置"
        mkdir -p /etc/zabbix/zabbix_agentd.d/
    fi
}

# 创建systemd服务
Create_systemd_service() {
    echo "创建systemd服务..."
    cat > /etc/systemd/system/zabbix-agent.service << EOF
[Unit]
Description=Zabbix Agent
After=network.target

[Service]
Type=simple
ExecStart=/opt/zabbix/sbin/zabbix_agentd -f -c /opt/zabbix/etc/zabbix_agentd.conf
ExecReload=/bin/kill -HUP \$MAINPID
Restart=on-failure
KillMode=process
RestartSec=10s
TimeoutSec=30s

[Install]
WantedBy=multi-user.target
EOF

    # 重新加载systemd
    systemctl daemon-reload
}

# 创建配置服务（用于不支持systemd的系统）
Create_init_service() {
    echo "创建init.d服务..."
    cat > /etc/init.d/zabbix-agent << 'EOF'
#!/bin/bash
#
# zabbix-agent     Start/Stop the Zabbix Agent daemon
#
# chkconfig: 2345 90 10
# description: Zabbix Agent
# processname: zabbix_agentd
# config: /opt/zabbix/etc/zabbix_agentd.conf
# pidfile: /opt/zabbix/var/run/zabbix_agentd.pid

### BEGIN INIT INFO
# Provides: zabbix-agent
# Required-Start: $network $local_fs
# Required-Stop: $network $local_fs
# Default-Start: 2 3 4 5
# Default-Stop: 0 1 6
# Short-Description: Start/Stop Zabbix agent
### END INIT INFO

# Source function library.
. /etc/rc.d/init.d/functions

RETVAL=0
prog="Zabbix Agent"
ZABBIX_BIN="/opt/zabbix/sbin/zabbix_agentd"
ZABBIX_CONF="/opt/zabbix/etc/zabbix_agentd.conf"
ZABBIX_PID="/opt/zabbix/var/run/zabbix_agentd.pid"

start() {
    echo -n $"Starting $prog: "
    daemon $ZABBIX_BIN -c $ZABBIX_CONF
    RETVAL=$?
    echo
    [ $RETVAL -eq 0 ] && touch /var/lock/subsys/zabbix-agent
    return $RETVAL
}

stop() {
    echo -n $"Shutting down $prog: "
    killproc zabbix_agentd
    RETVAL=$?
    echo
    [ $RETVAL -eq 0 ] && rm -f /var/lock/subsys/zabbix-agent
    return $RETVAL
}

reload() {
    echo -n $"Reloading $prog: "
    killproc zabbix_agentd -HUP
    RETVAL=$?
    echo
    return $RETVAL
}

case "$1" in
    start)
        start
        ;;
    stop)
        stop
        ;;
    restart)
        stop
        start
        ;;
    reload)
        reload
        ;;
    status)
        status zabbix_agentd
        RETVAL=$?
        ;;
    *)
        echo $"Usage: $0 {start|stop|restart|reload|status}"
        RETVAL=1
esac

exit $RETVAL
EOF

    chmod +x /etc/init.d/zabbix-agent
    chkconfig --add zabbix-agent
    chkconfig zabbix-agent on
}

# 检查并配置防火墙
Configure_firewall() {
    echo "配置防火墙..."
    # 检查firewalld是否运行
    if systemctl is-active firewalld &>/dev/null; then
        firewall-cmd --permanent --add-port=10050/tcp
        firewall-cmd --reload
        echo "已在firewalld中开放10050端口"
    # 检查iptables是否可用
    elif which iptables &>/dev/null; then
        iptables -A INPUT -p tcp --dport 10050 -j ACCEPT
        service iptables save 2>/dev/null || true
        echo "已在iptables中开放10050端口"
    else
        echo "未检测到活动的防火墙服务"
    fi
}

# 执行安装流程
Set_hostname
Set_zabbix_conf

# 根据系统选择服务管理方式
if [ -d /etc/systemd/system ]; then
    Create_systemd_service
    systemctl enable zabbix-agent
    systemctl start zabbix-agent
    echo "已通过systemd启动Zabbix Agent"
else
    Create_init_service
    service zabbix-agent start
    echo "已通过init.d启动Zabbix Agent"
fi

Configure_firewall

# 检查安装状态
if pgrep zabbix_agentd >/dev/null; then
    echo "✅ Zabbix Agent 7.0.10 安装并启动成功!"
    echo "主机名: $HOSTNAME"
    echo "服务器地址: $ZBX_SERVER"
    echo "运行模式: $mode"
else
    echo "❌ Zabbix Agent启动失败，请检查日志文件: /var/log/zabbix/zabbix_agentd.log"
fi

# 清理临时文件
cd /
rm -rf $TEMP_DIR
echo "安装完成!"